package com.zeratul.common.lock.utils;

import cn.hutool.core.util.ObjectUtil;
import com.zeratul.common.core.utils.spring.SpringUtils;
import com.zeratul.common.lock.annotation.ZtLockType;
import com.zeratul.common.lock.lock.base.BaseZtLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 分布式锁工具类
 */
@Slf4j
public class ZtLockUtils {

    private static BaseZtLock baseZtLock;

    static {
        baseZtLock = SpringUtils.getBean(BaseZtLock.class);
        if (ObjectUtil.isNull(baseZtLock)) {
            log.warn("【分布式锁】未找到合适的分布式锁实现类");
        }
    }

    /**
     * 阻塞锁
     */
    public static void lock(ZtLockType ztLockType, String key){
        if (ObjectUtil.isNull(baseZtLock)) {
            return;
        }
        baseZtLock.lock(ztLockType, key);
    }

    /**
     * 非阻塞锁
     * @param key
     * @param timeout
     * @return
     */
    public static boolean tryLock(ZtLockType ztLockType, String key, Integer timeout){
        if (ObjectUtil.isNull(baseZtLock)) {
            return false;
        }
        return baseZtLock.tryLock(ztLockType, key, timeout);
    }

    /**
     * 解锁
     */
    public static void unlock(){
        if (ObjectUtil.isNull(baseZtLock)) {
            return;
        }
        baseZtLock.unlock();
    }
}
